package com.anjie.powerproject.service.impl;

import com.anjie.powerproject.common.MockDataUtil;
import com.anjie.powerproject.entity.PreStrategy;
import com.anjie.powerproject.repository.PreStrategyRepository;
import com.anjie.powerproject.service.PreStrategyService;
import com.anjie.powerproject.strategy.utils.DateUtils;
import com.anjie.powerproject.util.DateRange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class PreStrategyServiceImpl implements PreStrategyService {
    @Autowired
    PreStrategyRepository preStrategyRepository;

    @Autowired
    MockDataUtil mockDataUtil;

    @Autowired
    Environment env;

    @Override
    public List<List<PreStrategy>> getPreStrategyByCodeAndDateRange(Integer code, Integer modelVersion, Date startTime, Date endTime,Integer strategyType) {
        if (Arrays.asList(env.getActiveProfiles()).contains("dev")) {
            return mockDataUtil.buildPreStrategyList(startTime, endTime);
        }

        Date limitDate = DateUtils.plusOrMinusDay(endTime, 1).getTime();
        String start = DateUtils.ymdFormat.format(startTime);
        String end = DateUtils.ymdFormat.format(limitDate);

        List<PreStrategy> preStrategies = preStrategyRepository.getPreStrategy(modelVersion, start, end, strategyType);

        List<String> dateList = DateRange.getDateListOfDateRange(startTime, endTime);
        // 按时间划分
        Map<String, List<PreStrategy>> preStrategyMap = preStrategies.stream().collect(Collectors.groupingBy(e -> DateUtils.ymdFormat.format(e.getStartTime())));

        List<List<PreStrategy>> preStrategyList = new ArrayList<>();
        for (String date : dateList) {
            preStrategyList.add(preStrategyMap.get(date));
        }

        return preStrategyList;
    }
}
